#!/usr/bin/env python
# coding=utf-8


import logging
from flask import request, g, redirect, url_for, render_template
from over.model import db, Product, CartItem
from over.handlers.router import Router
from over.handlers.my import mod
from over.handlers.helper import random_str, jsonify

router = Router()
logger = logging.getLogger("my.cart")


@router('/cart')
class Cart(object):
    @router('/')
    def index(self):
        cart_items = CartItem.get_items(g.user.id)
        return render_template('my/cart/index.html', cart_items=cart_items, cart_num=len(cart_items))

    @router('/add', methods=['POST'])
    def add(self):
        pid = request.form.get('product')
        print(pid)
        prod = Product.query.get_or_404(pid)

        cart_item = CartItem(title=prod.title, price=prod.price, product_id=pid,
                             description=prod.description, user_id=g.user.id,
                             period=prod.period, index=random_str(32))
        db.session.add(cart_item)
        db.session.commit()

        return redirect(url_for('.index'))

    @router('/remove', methods=['POST'])
    def remove(self):
        index = request.form.get('index')
        cart_items = CartItem.get_items(g.user.id)

        item_value = None
        for cart_item in cart_items:
            if cart_item.index == index:
                item_value = cart_item
                break

        if item_value is not None:
            item_value.is_deleted = True
            db.session.add(item_value)
            db.session.commit()

            return jsonify({'success': True, 'number': len(cart_items) - 1})
        else:
            return jsonify({'success': False, 'error': u'不存在的购物车项'})


router.register_url_rules(mod)
